This post provides a quick derivation of the fast Fibonacci
doubling formulas, using the correspondence between Fibonacci numbers
and the number of ways to climb
The Fibonacci numbers are a sequence
The Fibonacci doubling formulas are:
These formulas can be used to efficiently compute Fibonacci numbers (see the the end of the post for how). They are usually derived from a matrix power representation of Fibonacci numbers (or see one of my earlier posts for an alternative). This blog post gives a direct combinatorial derivation.
There’s a well-known algorithmic problem of counting the number of ways,
We can count solutions to the steps problem in a different way, by dividing the problem in two (treating even and odd separately).
First the even case. Suppose we have
The odd case is similar. Suppose we have
Since
For completeness, here’s how to use these formulae to quickly compute Fibonacci numbers with
def fib2(n):
"""fib2(n) returns fib(n), fib(n+1)"""
if n == 0:
return 0, 1
f0, f1 = fib2(n//2)
if n % 2 == 0:
# Even case.
return 2*f0*f1 - f0*f0, f0*f0 + f1*f1
else:
# Odd case.
# We need to return fib(2k+1), fib(2k+2)
# and we have f0=fib(k), f1=fib(k+1).
# The doubling formulas give:
# fib(2k) = 2*f0*f1 - f0*f0, fib(2k+1)=f0*f0 + f1*f1
# Then fib(2k+2) = fib(2k) + fib(2k+1) = 2*f0*f1 + f1*f1.
return f0*f0 + f1*f1, 2*f0*f1 + f1*f1
for i in range(20):
print(i, fib2(i)[0])